package com.powerdata.framework.dataSource;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;

public class DataSourceSwitcher {
	private static final Logger logger = Logger.getLogger(DataSourceSwitcher.class);

	private static final String DATASOURCE_MASTER = "master";
	private static final String DATASOURCE_SLAVE = "slave";
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

	public static void setDataSource(String dataSource) {
		Assert.notNull(dataSource, "dataSource cannot be null");
		contextHolder.set(dataSource);
	}

	public static void setMaster(){
		clearDataSource();
		setDataSource(DATASOURCE_MASTER);
		logger.info("启用主数据库连接master");
    }

	public static void setSlave() {
		clearDataSource();
		setDataSource(DATASOURCE_SLAVE);
		logger.info("启用从数据库连接slave");
	}

	public static String getDataSource() {
		Object o = contextHolder.get();
		if (o == null)
			return DATASOURCE_MASTER;
		return (String) o;
	}

	public static void clearDataSource() {
		contextHolder.remove();
	}
	
}


